package com.xiaoxiong.gobang.ai;

import android.util.Log;

import com.xiaoxiong.gobang.bean.GameState;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * @author xiaoxiong
 * @Package com.xiaoxiong.gobang.ai
 * @Description:第三个AI算法
 * @email 249900679@qq.com
 * @date 2016/4/1 17:40
 */
public class ThirdAi implements Searcher {

    private GameState gameState;
    private int depth;
    private int pos;
    private List<Integer> chessDis;
    private Set<Integer> nullPos;

    @Override
    public int SearchBestPlay(GameState state, int depth) {
        Log.d("isuse", "yes");
        this.gameState = state;
        this.depth = depth;
        this.nullPos = new HashSet<>();
        pos = 0;
        chessDis = new ArrayList<>();
        FirstAiSearcher();
        int len = chessDis.size();
        if (len > 0) {
            Random random = new Random();
            int dis = random.nextInt(len);
            pos = chessDis.get(dis);
            chessDis.clear();
        }
        Log.d("isuse", "" + pos);
        if (pos == 0) {
            Random random = new Random();
            int dis = random.nextInt(256);
            while (!gameState.checkDis(dis)) {
                dis = random.nextInt(256);
            }
            pos = dis;
        }
        Log.d("pos---", ".." + pos);
        return pos;
    }

    /**
     * 查找落子点
     *
     * @return
     */
    private int FirstAiSearcher() {

        int score = 0;
        nullPos = gameState.getNullPos();
        Object[] canPutChess = nullPos.toArray();
        int len = canPutChess.length;
        Log.d("length", len + "");
        while (len-- != 0) {
            int i = (int) canPutChess[len];
            int s1 = 0;
            int s2 = 0;
            if (gameState.checkDis(i)) {
                //我方在该位置下棋
                if (gameState.PutChess(i, true)) {
                    gameState.BackChess(i, true);
                    pos = i;
                    chessDis.clear();
                    return 999999999;
                }
                s1 = gameState.Evaluate(i, depth);
                gameState.BackChess(i, true);
                //对方在该位置下棋
                if (gameState.PutChess(i, false)) {
                    gameState.BackChess(i, false);
                    chessDis.clear();
                    //即使对方能赢我也先不挡，先检查剩下的格子我是否能赢，所以分数要比我方赢的分数小一点
                    s2 = 999999990;
                } else {
                    s2 = gameState.Evaluate(i, depth) - 9;
                    gameState.BackChess(i, false);
                }
                s1 = s1 > s2 ? s1 : s2;

                if (s1 > score) {
                    chessDis.clear();
                    chessDis.add(i);
                    score = s1;
                } else if (s1 == score) {
                    chessDis.add(i);
                }
            }
        }
        return score;
    }
}
